package com.gp.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

@Configuration
@EnableResourceServer //开启资源服务器。
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceConfig extends ResourceServerConfigurerAdapter {
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Autowired
    private PasswordEncoder passwordEncoder;
    //设置Token的你的存放方式
    @Bean
    public TokenStore tokenStore(){
        JwtTokenStore jwtTokenStore=new JwtTokenStore(jwtAccessTokenConverter()); //参数表示：谁生成的token
        return jwtTokenStore;
    }
    //获取token的生成器.
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){ //默认会把第三方的账号 和 返回  以及自己的账号和权限生成进去。
        JwtAccessTokenConverter jwtAccessTokenConverter=new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey("123456");//token 密钥 不能外传
        return jwtAccessTokenConverter;
    }

    //告诉资源管理器从哪个位置获取token
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(tokenStore());
    }

    //设置不登录也可以访问的资源路径
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //order下的资源允许匿名访问
        http.authorizeRequests().antMatchers("/order/**").permitAll();
    }

}